// axios实例，适用在mock数据
import axios from 'axios'
import router from '@/router/index'
import store from '@/store/index'
import {getToken, clearToken} from '@/api/cache'
import {Loading, Message} from 'element-ui'
import {BASIC_URL, AXIOS_TIME_OUT, AXIOS_WITH_CREDENTIALS, IS_SUCCESS} from '@/api/config'
const instance = axios.create({
  baseURL: BASIC_URL,
  timeout: AXIOS_TIME_OUT,
  headers: {
    'X-Custom-Header': 'foobar',
    post: {
      'Content-Type': 'application/json; charset=utf-8'
    }
  },
  withCredentials: AXIOS_WITH_CREDENTIALS
})
// 请求拦截器
let loadingInstace = null
instance.interceptors.request.use(
  req => {
    loadingInstace = Loading.service({
      fullscreen: true,
      background: 'transparent'
    })
    let isLogin = store.dispatch('isLogin')
    req.headers.token = isLogin && getToken()
    return req
  },
  err => {
    loadingInstace.close()
    Message.error({
      message: '加载超时'
    })
    return Promise.reject(err)
    // return Promise.reject(err.data.error.message)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  res => {
    loadingInstace.close()
    // if (res.data && res.data.code !== IS_SUCCESS) {
    //   Message.error({
    //     //  饿了么的消息弹窗组件,类似toast
    //     message: res.data.msg
    //   })
    //   // return Promise.reject(res.data.error.message)
    //   return Promise.reject(res)
    // }
    if (res.data.code === 401) {
      clearToken()
      Message.error('您的登录状态已失效，请重新登录！')
      router.replace({
        path: '/login'
      })
    } else {
      return res
    }
  },
  err => {
    // 拦截401错误
    loadingInstace.close()
    if (err.response) {
      switch (err.response.status) {
        case 401:
          console.log('响应拦截器....')
          // 这里写清除token的代码
          clearToken()
          router.replace({
            path: 'login'
          })
          break
        default:
          // Message.error({
          //   message: '加载失败'
          // })
          break
      }
    }
    return Promise.reject(err)
  }
)

// 封装axios 的 get 方法
export function axiosGetMock (url, param = {}, data = {}) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'get',
      params: param,
      data: data
    }).then(
      res => {
        resolve(res.data)
      },
      err => {
        reject(err)
      }
    )
  })
}

// 封装axios 的 post 方法
export function axiosPostMock (url, param = {}, data = {}) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'post',
      params: param,
      data: data
    }).then(
      res => {
        resolve(res.data)
      },
      err => {
        reject(err)
      }
    )
  })
}

export function axios$Mock (param) {
  return new Promise((resolve, reject) => {
    instance(param).then(
      res => {
        resolve(res)
      },
      err => {
        reject(err)
      }
    )
  })
}

export function axiosAllMock (arr = []) {
  return Promise.all(arr).then(
    (res) => {
      return new Promise((resolve, reject) => {
        if (res.length) {
          resolve(res)
        } else {
          reject(res)
        }
      })
    },
    err => {
      Promise.reject(err)
    }
  )
}
